package com.zengqingfa.springboot.validation.demo.controller;

import com.zengqingfa.springboot.validation.demo.entity.UserSaveDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.ConstraintViolation;
import java.util.Set;


@RestController
@RequestMapping("/user5")
@Slf4j
public class UserRest5 {

    @Autowired
    private javax.validation.Validator globalValidator;

    // 编程式校验
    @PostMapping("/create")
    public String saveWithCodingValidate(@RequestBody UserSaveDto user) {
        Set<ConstraintViolation<UserSaveDto>> validate = globalValidator.validate(user);
        // 如果校验通过，validate为空；否则，validate包含未校验通过项
        if (validate.isEmpty()) {
            // 校验通过，才会执行业务逻辑处理

        } else {
            for (ConstraintViolation<UserSaveDto> violation : validate) {
                // 校验失败，做其它逻辑
                System.out.println(violation.getMessage());
            }
        }
        return "save success";
    }


}
